package com.lxw;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer04_routing_email {
    //队列名
    private static final String QUEUE_TOPICS_EMAIL = "queue_topics_email";
    private static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";

    public static void main(String[] args)throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");

        //创建一个连接
        Connection connection = connectionFactory.newConnection();
        //创建与交换机的通道，每个通道代表一个会话
        Channel channel = connection.createChannel();
        /**
         * exchangeDeclare(交换机名称，交换机类型)
         * 交换机的类型有：fanout、topic、direct、headers
         */
        channel.exchangeDeclare(EXCHANGE_TOPICS_INFORM, BuiltinExchangeType.TOPIC);
        channel.queueDeclare(QUEUE_TOPICS_EMAIL,true,false,false,null);
        channel.queueBind(QUEUE_TOPICS_EMAIL,EXCHANGE_TOPICS_INFORM,"all.sms.email.#.aa");

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                long deliveryTag = envelope.getDeliveryTag();
                String exchange = envelope.getExchange();
                String routingKey = envelope.getRoutingKey();
                System.out.println(routingKey);
                String message = new String(body,"utf-8");
                System.out.println(message);
            }
        };
        channel.basicConsume(QUEUE_TOPICS_EMAIL,true,defaultConsumer);
    }
}
